from __future__ import annotations

import  uuid

from datetime import datetime
from io import StringIO

from fastapi import Depends, APIRouter, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.orm import Session
from sqlalchemy.orm.sync import update
from starlette import status

from common.avatra import RandomAvatarsService
from common.RsaUtil import RsaUtil
from common.sqlalchemy_db import SqlalchemyX

from modules.User import User
from modules.http_resp import HttpResponse, ResponseSuccess, ResponseFail
from modules.mod import Group, GroupRelationship, Dialog
from service.ChattingMessageService import ChattingMessageService
from service.GroupDBService import GroupDBService
from service.GroupService import GroupService
from service.SocketService import SocketService


class RegisterReq(BaseModel):
    userName: str
    password: str

class LogoutReq(BaseModel):
    userId: str

router = APIRouter()

socketService: SocketService = SocketService()
groupdbService: GroupDBService = GroupDBService()
chattingMessageService: ChattingMessageService = ChattingMessageService()

@router.post("/register")
async def register(request: RegisterReq):
    username = request.userName
    password = request.password

    async with SqlalchemyX.AsyncSessionLocal() as session:
        user = await session.execute(select(User).filter(User.user_name == username).limit(1))
        if user.scalars().all():
            return ResponseFail(
                    msg=f"用户名'{username}'已存在！",
                )
        else:
            avatar_service = RandomAvatarsService()
            new_user = User()
            new_user.user_id = str(uuid.uuid4())
            new_user.user_name = username
            new_user.user_saltPassword = RsaUtil.sign(password)
            new_user.user_reg_time = datetime.now()
            new_user.user_state = 0
            new_user.user_avatar = await avatar_service.get_random_avatar_url()

            _id = await socketService.create_socket({})

            new_user.user_socketId = _id
            session.add(new_user)

            # 获取默认群组
            default_group = await groupdbService.get_default_group()
            if not default_group:
                raise ValueError("Default group not found")

            # 注册的成员默认加入默认群组
            group_relationship = GroupRelationship(
                user_id=new_user.user_id,
                group_id=default_group.group_id,
                top_if=0,
                group_member_type='普通'
            )
            session.add(group_relationship)

            # 获取默认群组的最后一条消息
            result = await chattingMessageService.get_last_message_mes_by_option({"message_to_id": group_relationship.group_id})
            last_message_id = result.message_id if result else None

            # 为注册成员创建默认dialog关系（与默认群组）
            dialog = Dialog(
                dialog_from_id=new_user.user_id,
                dialog_target_id=default_group.group_id,
                last_message_id=last_message_id,
                dialog_last_time=datetime.now()
            )
            session.add(dialog)

            # 提交事务
            await session.commit()
            await session.flush()

        return ResponseSuccess({"success": True})

@router.post("/logout")
async def logout(req: LogoutReq, db: Session = Depends(SqlalchemyX.get_db)):
     db.query(User).filter(User.user_id == req.userId).update({'user_state':0})
     return ResponseSuccess("退出登录成功")
